const HOST_URI = 'http://localhost:3000/web/api';

function _obj2uri(obj) {
    if (obj == null) {
        return "openid=" + wx.getStorageSync("openid");
    }

    var p = Object.keys(obj).filter(function(k) {
        // 检查空字符串并给出警告
        if (obj[k] === '') {
            console.warn('API 警告: 参数 "' + k + '" 为空字符串，已被过滤');
        }
        // 过滤掉空值、undefined 和 null
        return obj[k] !== '' && obj[k] !== null && obj[k] !== undefined;
    }).map(function (k) {
        return encodeURIComponent(k) + "=" + encodeURIComponent(obj[k]);
    }).join('&');
    
    // 添加 openid（如果存在的话）
    var openid = wx.getStorageSync("openid");
    if (openid) {
        p = p ? p + "&openid=" + encodeURIComponent(openid) : "openid=" + encodeURIComponent(openid);
    }
    
    return p;
}

function _search(o) {
    return HOST_URI + '/food?' + _obj2uri(o);
}

function _foodInfo(o) {
    return HOST_URI + "/food?" + _obj2uri(o);
}

function _eat(o) {
    return HOST_URI + "/eat?" + _obj2uri(o);
}

function _eatDates(o) {
    return HOST_URI + "/dates?" + _obj2uri(o);
}

function _wxLogin(o) {
    // 登录接口不需要 openid，只需要 code
    if (o && o.code) {
        return HOST_URI + "/login?code=" + encodeURIComponent(o.code);
    }
    return HOST_URI + "/login";
}

// 修改后的 exerciseInfo 函数
function exerciseInfo(o) {
    return HOST_URI + "/exercise?" + _obj2uri(o);
}

function _run(o) {
    return HOST_URI + "/run?" + _obj2uri(o);
}

function _userInfo(o) {
    return HOST_URI + "/user?" + _obj2uri(o);
}

function _scanCode(o) {
    return HOST_URI + "/scan/code?" + _obj2uri(o);
}

function _eatRank(o) {
    return HOST_URI + "/rank?" + _obj2uri(o);
}

function _eatCurrent(o) {
    return HOST_URI + "/current?" + _obj2uri(o);
}

function _register(o) {
    return HOST_URI + "/register?" + _obj2uri(o);
}

function _do(o) {
    return HOST_URI + "/do?" + _obj2uri(o);
}

// 导出所有函数
module.exports = {
    search: _search,
    foodInfo: _foodInfo,
    eat: _eat,
    eatDates: _eatDates,
    wxLogin: _wxLogin,
    exerciseInfo: exerciseInfo,  
    run: _run,
    userInfo: _userInfo,
    scanCode: _scanCode,
    eatRank: _eatRank,
    eatCurrent: _eatCurrent,
    register: _register,
    do: _do
};
